<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="/resource/css/bootstrap-table.min.css" type="text/css">

<!-- Latest compiled and minified JavaScript -->
<script src="/resource/js/bootstrap-table.min.js"></script>
<!-- Latest compiled and minified Locales -->
<script src="/resource/js/bootstrap-table-zh-CN.min.js"></script>

<div id="toolbar">
  <div class="btn-group ml-3" role="group" aria-label="Basic example">
    <button type="button" class="btn btn-info " onclick="AE()">添加</button>
  </div>
</div>
<div class="modal fade bd-example-modal-lg" id="AEModal" tabindex="-1" aria-labelledby="myLargeModalLabel"
  aria-hidden="true" style="display: none;">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="AEModalLongTitle">编辑</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <form id="AEForm">
          <input name="id" id="aeid" type="hidden">
          <div class="row">
            <div class="col">
              <div class="position-relative form-group">
                <label>类型</label>
                <select name="operate_type" class="form-control" data-style="btn-primary" id="operate_type_id">
                  <option value="1">充值</option>
                  <option value="2">消费</option>
                </select>
              </div>
            </div>
            <div class="col">
              <div class="position-relative form-group">
                <label >用户id</label>
                <input name="user_id" placeholder="用户id" type="number" class="form-control">
              </div>
            </div>
            <div class="col">
              <div class="position-relative form-group">
                <label >金额</label>
                <input name="amount" placeholder="金额" type="number" class="form-control">
              </div>
            </div>
            <div class="col" id="recharge_name_id">
              <div class="position-relative form-group">
                <label>充值类型</label>
                <select name="recharge_name" class="form-control" id="limit_payment_id">
                  <option value="人工充值">人工充值</option>
                </select>
              </div>
            </div>

            <div class="col" id="consumption_name_id" style="display:none;">
              <div class="position-relative form-group">
                <label>消费类型</label>
                <select name="consumption_name" class="form-control" id="limit_plan_id">
                  <option value="人工消费">人工消费</option>
                </select>
              </div>
            </div>
          </div>
          
          <!-- <div class="row">
            
            <div class="col">
              <div class="position-relative form-group">
                <label>订单号</label>
                <input name="transaction_id" id="transaction_id_id" placeholder="订单号" type="text" class="form-control">
              </div>
            </div>
          </div> -->
          
          <div class="position-relative form-group">
            <label>备注</label>
            <textarea name="remarks" class="form-control" rows="8"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" onclick="AEajax()">保存</button>
      </div>
    </div>
  </div>
</div>

<script>
  let planData;
  const $table = $('#table')
  let hasInit = false;
  $(function () {
    initTable()
    getShowPlan()
    getShowPayment()

    let operate_type_id = $("#operate_type_id")
    operate_type_id.change(function(){
      console.log(operate_type_id.val())
      switch (parseInt(operate_type_id.val())) {
        case 1:
          $("#recharge_name_id").show()
          $("#consumption_name_id").hide()
          break;
        case 2:
          $("#consumption_name_id").show()
          $("#recharge_name_id").hide()
          break;
      
        default:
          break;
      }

    })
  })

  var randomString = function(length) {
    var str = '';
    var chars ='0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split(
        '');
    var charsLen = chars.length;
    if (!length) {
      length = ~~(Math.random() * charsLen);
    }
    for (var i = 0; i < length; i++) {
      str += chars[~~(Math.random() * charsLen)];
    }
    return str;
  };
  
  //获取订阅列表
  function getShowPlan() {
    $.ajax({
        type: "POST",
        url: "/{{.setting.admin_path}}/plan/get_rtm1",
        dataType: "json",
        success: function(data) {
          if (data.code == 0) {
            console.log(data.data)
            for (let index = 0; index < data.data.data.length; index++) {
              const element = data.data.data[index];
              $("#limit_plan_id").append(`<option value="${element.name}">${element.name}</option>`)
            }
          }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            console.log(errorThrown)
            notify('danger', errorThrown)
        },
        complete: function () {//不管成功还是失败 都会进这个函数
          
        }
    });
  }

  //获取支付列表
  function getShowPayment() {
    $.ajax({
        type: "POST",
        url: "/{{.setting.admin_path}}/payment/get_show",
        dataType: "json",
        success: function(data) {
          if (data.code == 0) {
            console.log(data.data)
            for (let index = 0; index < data.data.data.length; index++) {
              const element = data.data.data[index];
              $("#limit_payment_id").append(`<option value="${element.name}">${element.name}</option>`)
            }
          }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            console.log(errorThrown)
            notify('danger', errorThrown)
        },
        complete: function () {//不管成功还是失败 都会进这个函数
          
        }
    });
  }
  
  //搜索
  function search() {
    $("#table").bootstrapTable('refresh',{pageNumber:1});
  }
  //清除搜索
  function cleanSearch() {
    $("select[data-function='search']").each(function (i, domEle) {
      // 选择第一个选项
      $(this).val($(this).find('option:first').val());
    })
    $("input[data-function='search']").each(function (i, domEle) {
      $(domEle).val("")
    })
    $("#table").bootstrapTable('refresh');
  }

  //AE表单
  function AE(data) {
    
    $('#AEForm')[0].reset();
    if (data != null) {
      $("#AEModalLongTitle").text("编辑")
      $("#AEForm input[type='hidden'],#AEForm input[type='number'],#AEForm input[type='text'],#AEForm select,#AEForm textarea").each(function (i, v) {

        if ($(v).attr('name') != 'remarks' && $(v).attr('name') != 'id') {
          $(v).attr('disabled','disabled')
        }

        for (let key in data.recharge_records) {
          if (key == $(v).attr("name")) {
            $(v).val(data.recharge_records[key])
          }
        }
      })

      $("#AEForm input[type='checkbox']").each(function (i, v) {
        for (let key in data.recharge_records) {
          if (key == $(v).attr("name")) {
            if (data.recharge_records[key] == 1) {
              $(v).attr("checked", "true")
            } else {
              $(v).removeAttr("checked")
            }
          }
        }
      })

    } else {
      $("#transaction_id_id").val(`manual${$.now()}${randomString(5)}`)
      $("#AEModalLongTitle").text("添加")
      $("#aeid").val("")

      $("#AEForm input[type='hidden'],#AEForm input[type='number'],#AEForm input[type='text'],#AEForm select,#AEForm textarea").each(function (i, v) {

        if ($(v).attr('name') != 'remarks') {
          $(v).removeAttr('disabled')
        }
      })
    }
    $('#AEModal').modal('show')
  }

  //ae提交
  function AEajax() {
    let d = {}
    let t = $("#AEForm").serializeArray();
    $.each(t, function () {
      d[this.name] = this.value;
    });
    let url = '';
    console.log(d)
    if (d.id != undefined && d.id != "") {
      url = "/{{.setting.admin_path}}/recharge_records/up_remarks"
    }else{
      url = "/{{.setting.admin_path}}/recharge_records/add"
    }
    $.ajax({
      type: "POST",
      url: url,
      data: d,
      dataType: "json",
      success: function (data) {
        if (data.code == 0) {
          notify('success', "保存成功")
        } else {
          notify('danger', data.message)
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log(errorThrown)
        notify('danger', errorThrown)
      },
      complete: function () {//不管成功还是失败 都会进这个函数
        $('#AEModal').modal('hide')
        $("#table").bootstrapTable('refresh');
      }
    });
  }

  //初始化表格
  function initTable() {
    $table.bootstrapTable({
      columns: [
        [
          {

          }, {
            title: '<input type="number"  placeholder="ID" class="form-control" name="id" data-function="search" data-type="eq"  />',
          }, {
            title: '',
          }, {
            title: '<input type="number"  placeholder="用户id" class="form-control" name="user_id" data-function="search" data-type="eq" />',
          }, {
            title: '<input type="text"  placeholder="用户名" class="form-control" name="user_name" data-function="search" data-type="like" />',
          }, {
            title: `<div class="input-group">
                    <select class="custom-select" data-function="search" data-type="eq" name="operate_type">
                      <option selected value="0">全部</option>
                      <option value="1">充值</option>
                      <option value="2">消费</option>
                    </select>
                  </div>`,
          }, {
            title: '<input type="text"  placeholder="充值类型" class="form-control" name="recharge_name" data-function="search" data-type="like" />',
          }, {
            title: '<input type="text"  placeholder="消费类型" class="form-control" name="consumption_name" data-function="search" data-type="like" />',
          }, {
            title: '<input type="text"  placeholder="备注" class="form-control" name="remarks" data-function="search" data-type="like" />',
          }, {
            title: '<input type="text"  placeholder="订单号" class="form-control" name="transaction_id" data-function="search" data-type="like" />',
            
          }, {
            title:  ``,
          }, {
            title: `

                  <div class="input-group">
                    <button type="button" class="btn btn-twitter btn-icon-only" onclick="search()">
                      <span class="btn-inner--icon"><i class="fas fa-search"></i></span>
                    </button>
                    <button type="button" class="btn btn-google-plus btn-icon-only" onclick="cleanSearch()">
                      <span class="btn-inner--icon"><i class="fas fa-trash"></i></span>
                    </button>
                  </div>
          `,
          },
        ], [
          {
            checkbox: true,
          }, {
            field: 'recharge_records.id',
            sortName:'id',
            title: 'ID',
            width: 80,
            sortable: true, //是否允许排序
            visible:false,//隐藏

          }, {
            field: 'recharge_records.amount',
            sortName:'amount',
            title: '金额',
            sortable: true, //是否允许排序
          }, {
            field: 'recharge_records.user_id',
            sortName:'user_id',
            title: '用户id',
            // visible:false,//隐藏
            sortable: true, //是否允许排序
          }, {
            field: 'user.user_name',
            title: '用户名',
            // visible:false,//隐藏
            sortable: false, //是否允许排序
          }, {
            field: 'recharge_records.operate_type',
            sortName:'operate_type',
            title: '类型',
            sortable: true, //是否允许排序
            formatter: function (value, row, index) {
              switch (row.recharge_records.operate_type) {
                case 1:
                  return `充值`;
                  break;
                case 2:
                  return `消费`;
                  break;
                default:
                  break;
              }
              
            }
          }, {
            field: 'recharge_records.recharge_name',
            sortName:'recharge_name',
            title: '充值类型',
            sortable: true, //是否允许排序
          }, {
            field: 'recharge_records.consumption_name',
            sortName:'consumption_name',
            title: '消费类型',
            sortable: true, //是否允许排序
          }, {
            field: 'recharge_records.remarks',
            sortName:'remarks',
            title: '备注',
            sortable: true, //是否允许排序
            formatter: function (value, row, index) {
              if (row.recharge_records.remarks != "") {
                return "有备注"
              }else{
                return "无备注"
              }
              
            }
          }, {
            field: 'recharge_records.transaction_id',
            sortName:'transaction_id',
            title: '订单号',
            sortable: true, //是否允许排序
          },{
            field: 'recharge_records.created_at',
            sortName: 'created_at',
            title: '创建时间',
            sortable: true, //是否允许排序
          },{
            field: 'operate',
            title: '操作',
            width:120,
            events: {
              'click #edit': function (e, value, row, index) {
                AE(row)
              },
            },
            formatter: function (value, row, index) {
              return `
              <div class="btn-group" role="group" aria-label="Basic example">
                <button id="edit" type="button" class="btn btn-twitter btn-icon-only"><span class="btn-inner--icon"><i class="fas fa-edit"></i></span></button>
              </div>`;
            }
          }
        ]
      ], //列
      url: '/{{.setting.admin_path}}/recharge_records',
      method: 'post', //请求方法
      dataType: 'json',//数据格式
      toolbar: '#toolbar',
      pagination: true, //是否显示页码
      sidePagination: "server",//服务器处理分页
      serverSort: "true",//是否服务器处理排序
      sortName:'id',
      sortOrder:'desc',
      showRefresh: true,  //显示刷新按钮
      showColumns: true, //是否显示列下拉列表按钮
      showFullscreen: true, //是否显示全屏按钮

      responseHandler: function (res) {  //response数据处理
        return {
          "rows": res.data.data,
          "total": res.data.totle,
        };
      },

      //搜索
      queryParams: function (x) {

        $("select[data-function='search']").each(function (i, domEle) {
          x[$(domEle).attr("name")] = domEle.value
        })

        $("input[data-function='search']").each(function (i, domEle) {
          const bindingDomID = $(domEle).attr("data-select-binding")
          if (bindingDomID != undefined) {
            x[$(bindingDomID).attr("name")] = $(bindingDomID).val()
          }
          x[$(domEle).attr("name")] = domEle.value
        })


        return x
      },
      onColumnSwitch:function(field,checked) { //列选择事件
        window.localStorage.setItem('recharge_records_hidden_columns', JSON.stringify($("#table").bootstrapTable('getHiddenColumns').map(function (it) {return it.field})))
        
      },
      onPostBody:function(data){//渲染并在 DOM 中可用后触发
        
        if (hasInit == false &&window.localStorage.getItem('recharge_records_hidden_columns') != null) {
          JSON.parse(window.localStorage.getItem('recharge_records_hidden_columns')).forEach(v => {
            $("#table").bootstrapTable('hideColumn', v);
          });
        }
        if (!hasInit) hasInit = true
      },

    })
  }

  document.addEventListener('keyup', function(event) {
    if (event.keyCode === 13) {
        // 回车键按下后的操作
        search()
    }
  });
</script>